package com.ebelter.myehc.ui.activitys;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ebelter.btcomlib.CommonLib;
import com.ebelter.btcomlib.common.Constants;
import com.ebelter.btcomlib.models.beans.ScaleUser;
import com.ebelter.btcomlib.models.bluetooth.base.BlueManager;
import com.ebelter.btcomlib.models.bluetooth.bean.ProductStyle;
import com.ebelter.btcomlib.models.bluetooth.products.bloodoxgen.bean.BOMesureResultBean;
import com.ebelter.btcomlib.models.bluetooth.products.bpm.BPMConstant;
import com.ebelter.btcomlib.models.bluetooth.products.bpm.BpmManager;
import com.ebelter.btcomlib.models.bluetooth.products.bpm.bean.BpmMesureResult;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.BraceletManager;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.BraDb;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.RateBean;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.SleepInfo;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.WalkBean;
import com.ebelter.btcomlib.models.bluetooth.products.ear_temperature.EarTemperatureManager;
import com.ebelter.btcomlib.models.bluetooth.products.ear_temperature.bean.EarTemMesureResult;
import com.ebelter.btcomlib.models.bluetooth.products.scale.bean.ScaleMeasureResult;
import com.ebelter.btcomlib.models.bluetooth.products.three2one.bean.ThreeOneMesureResultBean;
import com.ebelter.btcomlib.models.eventbus.CommonEventBus;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.utils.CommonUtils;
import com.ebelter.btcomlib.utils.GpsUtil;
import com.ebelter.btcomlib.utils.StringUtils;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.btcomlib.views.dialogs.LoadingDialog;
import com.ebelter.btcomlib.views.dialogs.TextTipDialog;
import com.ebelter.myehc.R;
import com.ebelter.myehc.beans.BraTodayData;
import com.ebelter.myehc.models.http.request.EhcNetUtils;
import com.ebelter.myehc.models.http.response.GetPersonInfoFromBT;
import com.ebelter.myehc.models.http.upload.UpLoadUtil;
import com.ebelter.myehc.models.managers.AMesuresCalBack;
import com.ebelter.myehc.models.managers.EhcManager;
import com.ebelter.myehc.models.ota.DfuService;
import com.ebelter.myehc.models.ota.OtaManager;
import com.ebelter.myehc.models.update.Updater;
import com.ebelter.myehc.ui.fragments.BG_Fragment;
import com.ebelter.myehc.ui.fragments.BO_Fragment;
import com.ebelter.myehc.ui.fragments.BPM_Fragment;
import com.ebelter.myehc.ui.fragments.BRA_Fragment;
import com.ebelter.myehc.ui.fragments.ET_Fragment;
import com.ebelter.myehc.ui.fragments.Scale_Fragment;
import com.ebelter.myehc.ui.fragments.TCH_Fragment;
import com.ebelter.myehc.ui.fragments.UA_Fragment;
import com.ebelter.myehc.ui.fragments.modifys.ModifyBirthday_Fragment;
import com.ebelter.myehc.ui.fragments.modifys.ModifyHeight_Fragment;
import com.ebelter.myehc.ui.fragments.modifys.ModifySex_Fragment;
import com.ebelter.myehc.ui.fragments.modifys.ModifyShHSet_Fragment;
import com.ebelter.myehc.ui.fragments.modifys.ModifyWeight_Fragment;
import com.ebelter.myehc.utils.EHCCommonUtils;
import com.raizlabs.android.dbflow.sql.language.Delete;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import no.nordicsemi.android.dfu.DfuProgressListener;
import static com.ebelter.myehc.ui.activitys.LoginActivity.getAgeByBirthday;
import static com.ebelter.myehc.ui.activitys.LoginActivity.getBirthdayIntValue;


/**
 * zcq 13826672468
 */
public class MainActivity extends EhcBaseActivity implements View.OnClickListener {

    public static final String TAG = "MainActivity";
    DrawerLayout mDrawerLayout;

    private ImageView top_left_iv;
    private ImageView bluetooth_connect_station_iv;
    private TextView top_right_tv;
    private TextView top_title_tv;

    private LinearLayout m_left_ll;
    private TextView ll_userName_tv;

    private TextView m_0_tv;
    private TextView m_1_tv;
    private TextView m_2_tv;
    private TextView m_3_tv;
    private TextView m_4_tv;
    private TextView m_5_tv;
    private TextView m_6_tv;
    private TextView m_7_tv;

    private TextView m_left_ll_shhshj;

    private OtaManager mOtaManager;


    private int curDisProduct = -1;//当前显示的产品类型


    private String authKey;

    private EhcManager mEhcManager;
    private AMesuresCalBack mesuresCalBack;

    private UpLoadUtil mUpLoadUtil;

    private Updater mUpdater;
    private static final int What_Open_gps =77;


    @Override
    protected int loadLayoutById() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        super.initView();
        // UserSpUtil.writeString(AUTH_KEY,"LTEjNiM5IzkyIzE1MzQ3MjkwNjgwNTgjNDQwMzA2MDAzMDEzNzI1NDkjMQ==");
        EventBus.getDefault().register(this);
        FV();
        setListeners();
        tryOpenBluetooth();

    }


    private ProgressDialog progressDialog;
    public void showProgressDialog() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle(R.string.zhzshj);
        progressDialog.setMessage(CommonLib.getString(R.string.qshd));
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);
        progressDialog.setMax(100);
        progressDialog.show();
    }

    public void setProgressDialog(int p) {
        if (progressDialog!=null)progressDialog.setProgress(p);
    }
    public void dissProgressDialog() {
        if (progressDialog!=null)progressDialog.cancel();
    }

    private void stopDfu() {
        Intent intent = new Intent(this, DfuService.class);
        stopService(intent);
    }

    private void tryOpenBluetooth() {
        if (!BlueManager.getInstance().isBluetoothOpen()){
            BlueManager.getInstance().openBluetooth3(this);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(CommonEventBus event) {
        if (!TextUtils.equals(event.whichReceive, TAG)) {
            return;
        }
        LogUtils.i(TAG, "MainActivity--onEventMainThread接收到CommonEventBus信息--" + event.toString());

        if (TextUtils.equals(event.from, BraceletManager.TAG) || TextUtils.equals(event.from, EhcManager.TAG)) {//说明来自BraceletManager EhcManager消息
            if (event.cmd == 1) {
                //打开对话框
                showLoadingDialog2(getString_(R.string.sysDataing));
            } else if (event.cmd == 2) {
                //关闭对话框
                dissLoadingDialog2();
            }
        }


        if (TextUtils.equals(event.from, ModifyShHSet_Fragment.TAG)) {//下发手环心率周期时间
            int min = event.cmd;
            LogUtils.i(TAG, "下发手环心率周期时间 min = " + min);
            if (mEhcManager != null) mEhcManager.setBraXlZhq(min);
        }

        if (TextUtils.equals(event.from, ModifySex_Fragment.TAG)) {//更改了性别 重新下发用户信息
            LogUtils.i(TAG, "更改了性别 重新下发用户信息");
            if (mEhcManager != null) mEhcManager.sendUserInfo2Scale();
        }

        if (TextUtils.equals(event.from, ModifyBirthday_Fragment.TAG)) {//更改了年龄 重新下发用户信息
            LogUtils.i(TAG, "更改了生日 重新下发用户信息");
            if (mEhcManager != null) mEhcManager.sendUserInfo2Scale();
        }
        if (TextUtils.equals(event.from, ModifyHeight_Fragment.TAG)) {//更改了身高 重新下发用户信息
            LogUtils.i(TAG, "更改了身高 重新下发用户信息");
            if (mEhcManager != null) mEhcManager.sendUserInfo2Scale();
        }
        if (TextUtils.equals(event.from, ModifyWeight_Fragment.TAG)) {//更改了体重 重新下发用户信息
            LogUtils.i(TAG, "更改了体重 重新下发用户信息");
            if (mEhcManager != null) mEhcManager.sendUserInfo2Scale();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (mEhcManager != null) mEhcManager.startAutoCheck(0);

        mOtaManager.registerProgressListener(this);
        mOtaManager.startUpdate2(this);

        checkGpsDialog();
    }

    private TextTipDialog openGPSDialog;
    private void checkGpsDialog() {

        boolean isOpenGps = GpsUtil.isOpenGps(this);
        if (!isOpenGps){
            if (openGPSDialog == null) {
                openGPSDialog = new TextTipDialog(this, StringUtils.getResStr(R.string.open_gps_tip));
                openGPSDialog.setListener(new TextTipDialog.ICancelOkBtListener() {
                    @Override
                    public void cancel(Dialog dialogView) {

                    }

                    @Override
                    public void ok(Dialog dialogView) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(intent,What_Open_gps);
                        dialogView.cancel();
                    }
                });
            }
            if (!openGPSDialog.isShowing()) {
                openGPSDialog.show();
                openGPSDialog.setNativebtVisibility(View.GONE);
                openGPSDialog.setPositive_btBg(R.drawable.sp_018cd1_r6);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mEhcManager != null) {
            mEhcManager.stopAutoCheck();
            mEhcManager.disConnectDevice(true);
        }
        mOtaManager.unRegisterProgressListener(this);
    }

    @Override
    protected boolean isOpenBlueStationListener() {
        return true;//打开蓝牙监听器的意思
    }

    @Override
    protected void bluetoothStationReceive(Intent intent, String action) {
        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
            switch (state) {
                case BluetoothAdapter.STATE_OFF:
                    ToastUtil.show(getString_(R.string.close_blue_tip));//打开蓝牙提示语
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    break;
                case BluetoothAdapter.STATE_ON:
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    break;
            }
        }
    }

    private void setListeners() {
        top_left_iv.setOnClickListener(this);
        top_right_tv.setOnClickListener(this);

        m_0_tv.setOnClickListener(this);
        m_1_tv.setOnClickListener(this);
        m_2_tv.setOnClickListener(this);
        m_3_tv.setOnClickListener(this);
        m_4_tv.setOnClickListener(this);
        m_5_tv.setOnClickListener(this);
        m_6_tv.setOnClickListener(this);
        m_7_tv.setOnClickListener(this);
        m_left_ll.setOnClickListener(this);


        mesuresCalBack = new AMesuresCalBack() {
            @Override
            public void onConnected(ProductStyle productStyle, BluetoothDevice device) {
                LogUtils.i(TAG, "----onConnected:" + productStyle.getProductName() + "---onConnected");
                if (mEhcManager!=null){
                    mEhcManager.stopAutoCheck();
                    mEhcManager.isOtaUpdate = false;
                }

                if (productStyle==ProductStyle.BRACELET){

                    if (mEhcManager!=null&&mEhcManager.mBracetManager!=null){
                        if (!TextUtils.isEmpty(mEhcManager.mBracetManager.version)){
                            if (!TextUtils.equals(mEhcManager.mBracetManager.version,OtaManager.VERSION)){
                                LogUtils.i(TAG,"发现连接着的手环版本信息与此apk的版本信息----不一致--将显示侧边栏按钮");
                                ViewUtils.displayView(m_left_ll_shhshj);//如果连接成功的是手环 侧边栏打开
                            }else {
                                LogUtils.i(TAG,"发现连接着的手环版本信息与此apk的版本信息----一致--将不显示侧边栏按钮");
                              //  ViewUtils.displayView(m_left_ll_shhshj);//如果连接成功的是手环 侧边栏打开
                                //ToastUtil.show();
                            }
                        }
                    }

                }
                ViewUtils.setImageResource(bluetooth_connect_station_iv,R.drawable.ic_connected);

            }

            @Override
            public void onConnecting(ProductStyle productStyle, BluetoothDevice device) {
                LogUtils.i(TAG, "----onConnected:" + productStyle.getProductName() + "---onConnecting");
                ViewUtils.setImageResource(bluetooth_connect_station_iv,R.drawable.ic_connecting);
            }

            @Override
            public void onDisConnected(ProductStyle productStyle) {
                LogUtils.i(TAG, "----onDisConnected:" + productStyle.getProductName() + "---onDisConnected");
                ViewUtils.setImageResource(bluetooth_connect_station_iv,R.drawable.ic_unconnect);
                if (productStyle==ProductStyle.BRACELET){
                    dissLoadingDialog2();
                    //ViewUtils.goneView(m_left_ll_shhshj);//如果连接断开的是手环 侧边栏打开
                }
            }

            //---------------------------------------------------------血压计01
            @Override
            public void BPM_dynamicSystolicPressure(int value) {
                super.BPM_dynamicSystolicPressure(value);
                LogUtils.i(TAG, "BPM_dynamicSystolicPressure--Value = " + value);
                // if (mBPM_Fragment!=null)mBPM_Fragment.setBPM_dynamicSystolicPressure(value);
            }

            @Override
            public void BPM_measureError(String conName,int errorType) {
                super.BPM_measureError(conName,errorType);
                LogUtils.i(TAG, "BPM_measureError--errorType = " + errorType+" ---connectName = "+conName);

                if (TextUtils.equals(BPMConstant.BPM_NAME,conName)){
                    ToastUtil.show(BpmManager.getErrorInfoDesc(errorType));
                }else {
                    ToastUtil.show(BpmManager.getErrorInfoDesc2(errorType));
                }

            }

            @Override
            public void BPM_measureResult(BpmMesureResult mesureResult) {
                super.BPM_measureResult(mesureResult);

                ToastUtil.show(R.string.Uploaded_successfully);

                LogUtils.i(TAG, "BPM_measureResult--BpmMesureResult = " + mesureResult.toString());
                if (mBPM_Fragment != null) mBPM_Fragment.setBpmMesureResult(mesureResult);
                mesureResult.authKey = authKey;
                if (mUpLoadUtil!=null)mUpLoadUtil.upLoadBloodPressure(true, mesureResult);
            }
            //---------------------------------------------------------血压计02


            //---------------------------------------------------------血氧01
            @Override
            public void BO_mesureing(int value) {
                super.BO_mesureing(value);
                LogUtils.i(TAG, "BO_mesureing--value = " + value);
                //  value= Math.abs(value);
                //if (mBO_Fragment!=null)mBO_Fragment.setMesureing(value);
            }

            @Override
            public void BO_mesureResult(BOMesureResultBean resultBean) {
                super.BO_mesureResult(resultBean);
                LogUtils.i(TAG, "BO_mesureResult--resultBean = " + resultBean.toString());
                ToastUtil.show(getString_(R.string.Uploaded_successfully));
                if (mBO_Fragment != null) mBO_Fragment.setMesureResult(resultBean);
                resultBean.authKey = authKey;
                if (mUpLoadUtil!=null)mUpLoadUtil.upLoadBO(true, resultBean);
            }

            //---------------------------------------------------------血氧02


            //---------------------------------------------------------体温01

            @Override
            public void ET_error(int errorCode) {
                super.ET_error(errorCode);
                ToastUtil.show(EarTemperatureManager.getErrorCodeDesc(errorCode));
            }

            @Override
            public void ET_mesureResult(EarTemMesureResult result) {
                super.ET_mesureResult(result);
                LogUtils.i(TAG,"耳温枪--"+result.toString());
                ToastUtil.show(R.string.Uploaded_successfully);
                if (mET_Fragment != null) {
                    mET_Fragment.setEarTemMesureResult(result);
                }
                result.authKey = authKey;
                if (mUpLoadUtil!=null)mUpLoadUtil.upLoadEarTem(true, result);
            }


            //---------------------------------------------------------体温02

            //---------------------------------------------------------三合一01
            @Override
            public void ThreeOne_error(int errorCode) {
                super.ThreeOne_error(errorCode);
                if (errorCode == 1) {
                    ToastUtil.show(R.string.cljggd);
                } else if (errorCode == 2) {
                    ToastUtil.show(R.string.cljggg);
                }
                if (mBG_Fragment != null) mBG_Fragment.setMesureResult2Null();
                if (mUA_Fragment != null) mUA_Fragment.setMesureResult2Null();
                if (mTCH_Fragment != null) mTCH_Fragment.setMesureResult2Null();

            }

            @Override
            public void ThreeOne_mesureResult(ThreeOneMesureResultBean mesureResult) {
                super.ThreeOne_mesureResult(mesureResult);
                ToastUtil.show(R.string.Uploaded_successfully);
                mesureResult.authKey = authKey;
                //01血糖 02尿酸 03胆固醇
                if (mesureResult.product == 1) {
                    if (mUpLoadUtil!=null)mUpLoadUtil.upLoadThreeOne(true, mesureResult);
                    if (mBG_Fragment != null) mBG_Fragment.setMesureResult(mesureResult);
                } else if (mesureResult.product == 2) {
                    if (mUpLoadUtil!=null)mUpLoadUtil.upLoadThreeOne(true, mesureResult);
                    if (mUA_Fragment != null) mUA_Fragment.setMesureResult(mesureResult);
                } else if (mesureResult.product == 3) {
                    if (mUpLoadUtil!=null)mUpLoadUtil.upLoadThreeOne(true, mesureResult);
                    if (mTCH_Fragment != null) mTCH_Fragment.setMesureResult(mesureResult);
                }


            }
            //---------------------------------------------------------三合一02

            //---------------------------------------------------------体脂秤01

            @Override
            public void SCALE_onFatMeasureError(int type) {
                super.SCALE_onFatMeasureError(type);
                LogUtils.i(TAG, "-----SCALE_onFatMeasureError------type = " + type);
                if (ScaleUser.getUser().getAge() < 18) {
                    ToastUtil.show(R.string.select_age_tip);//未满18岁测脂错误提示
                } else {
                    ToastUtil.show(R.string.mesure_fat_error_tip);//测脂错误提示
                }
            }

            @Override
            public void SCALE_onReceiveMeasureResult(ScaleMeasureResult result) {
                super.SCALE_onReceiveMeasureResult(result);

                ToastUtil.show(R.string.Uploaded_successfully);
                result = CommonUtils.dealScaleMeasureResult(result);

                if (mScale_Fragment != null) {
                    mScale_Fragment.setMeasureResult(result);
                }

                if (result.mesureCode!=-1){
                    result.authKey = authKey;
                    if (mUpLoadUtil!=null)mUpLoadUtil.upLoadScale(true, result);
                }


            }
            //---------------------------------------------------------体脂秤02


            //---------------------------------------------------------手环01


            @Override
            public void sleepInfo(SleepInfo sleepInfo) {
                super.sleepInfo(sleepInfo);
                if (mBRA_Fragment != null) mBRA_Fragment.setSleepInfo(sleepInfo);
            }

            @Override
            public void Bra_setUserSuccess() {
                LogUtils.i(TAG, "手环设置用户信息成功");
            }

            @Override
            public void getRealTimeData(WalkBean walkBean) {
                super.getRealTimeData(walkBean);
                LogUtils.i(TAG, "手环获取实时数据成功" + walkBean.toString());
                if (mBRA_Fragment != null) mBRA_Fragment.setRealTimeData(walkBean);
            }


            @Override
            public void getRealTimeXlData(RateBean obj) {
                super.getRealTimeXlData(obj);
                LogUtils.i(TAG, "手环获取心率实时数据成功" + obj.toString());
                if (mBRA_Fragment != null) mBRA_Fragment.setRealTimeXLData(obj);
            }

            @Override
            public void Bra_setXlCycSuccess() {
                LogUtils.i(TAG, "手环设置心率周期成功");
            }

            @Override
            public void SetBraTodayData(BraTodayData braTodayData) {
                if (mBRA_Fragment != null) mBRA_Fragment.SetBraTodayData(braTodayData);
            }

            @Override
            public void sysHistoryDataFinish() {
                LogUtils.i(TAG, "手环历史数据同步完");
                if (mBRA_Fragment != null) {
                    if (mBRA_Fragment.getPageSelectedPosition() == 1) {
                        //说明此时用户正好在手环心率页面
                        if (mEhcManager != null && mEhcManager.mBracetManager != null) {
                            mEhcManager.mBracetManager.getHeartRate(true);
                        }
                    }
                }

                if (mUpLoadUtil != null) mUpLoadUtil.startUpLoadBraData();//开始上传手环数据


            }

            @Override
            public void SHH_open_ota_success() {
                super.SHH_open_ota_success();
                LogUtils.i(TAG, "手环进入OTA升级成功1");



                    if (mEhcManager!=null&&mEhcManager.mBracetManager!=null){

                        String connectAddress=mEhcManager.mBracetManager.getConnectAddress();

                        if (!TextUtils.isEmpty(connectAddress)){

                            ToastUtil.show(R.string.shhjrotashj);
                            mEhcManager.isOtaUpdate = true;
                            String newMac1 = connectAddress.substring(0, 15) + EHCCommonUtils.algorismToHEXString(EHCCommonUtils.hexStringToAlgorism(connectAddress.substring(15, 17)) + 1);
                            String newMac = newMac1.toUpperCase();

//                            Intent intent = new Intent(MainActivity.this,DfuUpdateActivity.class);
//                            intent.putExtra(DfuUpdateActivity.SRC_MAC,connectAddress.toUpperCase());
//                            intent.putExtra(DfuUpdateActivity.OTA_MAC,newMac);

                   //         startActivity(intent);
                            LogUtils.i(TAG, "手环进入OTA升级成功2 newMac = " + newMac);
                            mOtaManager.setOtaMac(newMac);
                            mOtaManager.startUpdate(MainActivity.this);


                        }


                    }




            }

            @Override
            public void SHH_lowpower() {
                super.SHH_lowpower();
                LogUtils.i(TAG, "手环电量低");
                ToastUtil.show(R.string.dld);
            }

            //---------------------------------------------------------手环02






        };


        //---------------------------------------------手环升级01
        mOtaManager = new OtaManager();
        mOtaManager.setmDfuProgressListener2(new DfuProgressListener() {
            @Override
            public void onDeviceConnecting(String deviceAddress) {
                LogUtils.i(TAG,"--------------onDeviceConnecting deviceAddress="+deviceAddress);
            }

            @Override
            public void onDeviceConnected(String deviceAddress) {
                LogUtils.i(TAG,"--------------onDeviceConnected deviceAddress="+deviceAddress);
            }

            @Override
            public void onDfuProcessStarting(String deviceAddress) {
                showProgressDialog();
                LogUtils.i(TAG,"--------------onDfuProcessStarting deviceAddress="+deviceAddress);
            }

            @Override
            public void onDfuProcessStarted(String deviceAddress) {
                LogUtils.i(TAG,"--------------onDfuProcessStarted deviceAddress="+deviceAddress);
            }

            @Override
            public void onEnablingDfuMode(String deviceAddress) {
                LogUtils.i(TAG,"--------------onEnablingDfuMode deviceAddress="+deviceAddress);
            }

            @Override
            public void onProgressChanged(String deviceAddress, int percent, float speed, float avgSpeed, int currentPart, int partsTotal) {
                LogUtils.i(TAG,"-------onProgressChanged--deviceAddress="+deviceAddress+"--percent="+percent+"---speed="+speed+"---avgSpeed="+avgSpeed);

                setProgressDialog(percent);

            }

            @Override
            public void onFirmwareValidating(String deviceAddress) {
                LogUtils.i(TAG,"--------------onFirmwareValidating deviceAddress="+deviceAddress);
            }

            @Override
            public void onDeviceDisconnecting(String deviceAddress) {
                LogUtils.i(TAG,"--------------onDeviceDisconnecting deviceAddress="+deviceAddress);
            }

            @Override
            public void onDeviceDisconnected(String deviceAddress) {
                LogUtils.i(TAG,"--------------onDeviceDisconnected deviceAddress="+deviceAddress);
            }

            @Override
            public void onDfuCompleted(String deviceAddress) {
                LogUtils.i(TAG,"--------------onDfuCompleted deviceAddress="+deviceAddress);
                ToastUtil.show(R.string.shhgjshjchg);
                LogUtils.i(TAG,"手环固件升级成功");
                dissProgressDialog();
                mEhcManager.startAutoCheck(0);
            }

            @Override
            public void onDfuAborted(String deviceAddress) {
                LogUtils.i(TAG,"--------------onDfuAborted deviceAddress="+deviceAddress);
            }

            @Override
            public void onError(String deviceAddress, int error, int errorType, String message) {
                LogUtils.i(TAG,"--------------onError deviceAddress="+deviceAddress+"--error="+error+"--errorType="+errorType+"--message="+message);
                LogUtils.i(TAG,"手环固件升级失败");
                ToastUtil.show(R.string.shhgjshjshb);
                mEhcManager.isOtaUpdate = false;
                dissProgressDialog();
                mEhcManager.startAutoCheck(0);

            }
        });

        //---------------------------------------------手环升级01

    }


    public static String getAuthKey() {
        return UserSpUtil.readString(Constants.IUser.AUTH_KEY);
    }


    @Override
    protected void initData() {
        super.initData();


        String ehc_phone_no = UserSpUtil.readInt(Constants.IUser.ehc_phone_no)+"";//左边侧边栏的显示资料名
        if (!TextUtils.isEmpty(ehc_phone_no)){
            ViewUtils.setTextViewStr(ll_userName_tv, ehc_phone_no);
        }

        //从后台同步一下数据
        sysUserInfoFromBt();


        initUserInfo();

        mEhcManager = new EhcManager(this.getApplicationContext());
        mEhcManager.setMesuresCalBack(mesuresCalBack);
        setButtomSelecter(0);

        mUpLoadUtil = UpLoadUtil.getInstance();
        // mUpLoadUtil.startCheck(); 检测缓存测量数据是否上传

        authKey = getAuthKey();
        LogUtils.i(TAG,"authkey = "+authKey);

        mUpdater=new Updater();
        updateVersion();
    }
    private void updateVersion() {
        mUpdater.checkVersion(this,false,false);
    }


    //保存从倍泰后台根据用户id查询的用户信息
    private void saveUserInfo(GetPersonInfoFromBT getPersonInfoFromBT) {


        if ( getPersonInfoFromBT==null || getPersonInfoFromBT.resultData==null ){
            return;
        }

        //  String userid = "000f0001000001";
        long userid2=10000000000000L+UserSpUtil.readInt(Constants.IUser.ehc_id,0);
        UserSpUtil.writeString(Constants.IUser.USER_ID,userid2+"");

        String btId = ScaleUser.toBtId(userid2+"");
        UserSpUtil.writeString(Constants.IUser.BT_ID,btId);


        UserSpUtil.writeInt(Constants.IUser.HEIGHT,getPersonInfoFromBT.resultData.height);//前面已经判断不空了 这里不需要再次判断
        UserSpUtil.writeFloat(Constants.IUser.WEIGHT,getPersonInfoFromBT.resultData.weight);

        UserSpUtil.writeString(Constants.IUser.BIRTHDAY,getPersonInfoFromBT.resultData.birthday);

        int year=getBirthdayIntValue(getPersonInfoFromBT.resultData.birthday,0,1990);
        UserSpUtil.writeInt(Constants.IUser.YEAR,year);
        UserSpUtil.writeInt(Constants.IUser.MONTHS,getBirthdayIntValue(getPersonInfoFromBT.resultData.birthday,1,6));
        UserSpUtil.writeInt(Constants.IUser.DAY,getBirthdayIntValue(getPersonInfoFromBT.resultData.birthday,2,1));
        UserSpUtil.writeInt(Constants.IUser.AGE,getAgeByBirthday(year));

        String sex1=getPersonInfoFromBT.resultData.sex;
        int sexInt;
        if (TextUtils.equals(sex1,"1")){//服务器那边的是0未知1男2女  我这边的是0男1女
            sexInt=0;
        }else{
            sexInt=1;
        }
        UserSpUtil.writeInt(Constants.IUser.SEX,sexInt);//0男1女
        UserSpUtil.writeInt(Constants.IUser.PROFESSION,0); //0普通人1运动员
        UserSpUtil.writeFloat(Constants.IUser.IMPEDANCE,500);
        UserSpUtil.writeBoolean(Constants.IUser.IS_KG_MODEL,true);

        //LogUtils.i(TAG,"倍泰后台返回来的authkey = "+getPersonInfoFromBT.resultData.authkey);
        UserSpUtil.writeString(Constants.IUser.AUTH_KEY,getPersonInfoFromBT.resultData.authkey);

        initUserInfo();

    }

    //从后台同步一下数据
    private void sysUserInfoFromBt() {
        int ehc_id=UserSpUtil.readInt(Constants.IUser.ehc_id,-1);
        if (ehc_id==-1){
            return;
        }
        showLoadingDialog(getString_(R.string.loging));
        EhcNetUtils.getInstance().queryUserIsExitById(this, ehc_id+"", new HttpResponse<GetPersonInfoFromBT>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, GetPersonInfoFromBT getPersonInfoFromBT, String s) {
                LogUtils.i(TAG,"-sysUserInfoFromBt--queryUserIsExist--s="+s);
                dissLoadingDialog();


                if (!isRequestSuccess){
                    //服务器请求失败
                    ToastUtil.show(R.string.Server_unresponsive_please_try_again_later);
                    Intent intent=new Intent(MainActivity.this,LoginActivity.class);
                    intent.putExtra(Constants.ServerIsException,true);
                    startActivity(intent);
                    finish();
                    return;
                }

                if (getPersonInfoFromBT!=null&&getPersonInfoFromBT.resultCode==1){

                    LogUtils.i(TAG,"-----------------说明用户已经存在---------------------------");
                    LogUtils.i(TAG,"---getPersonInfoFromBT = "+getPersonInfoFromBT.toString());
                    saveUserInfo(getPersonInfoFromBT);
                    initUserInfo();

                }else {
                    LogUtils.i(TAG,"-----------------说明用户不存在---------------------------");
                    //用户不存在就跳到保存用户信息界面
                    Intent intent = new Intent(MainActivity.this,ModifyInfoActivity.class);
                    intent.putExtra(ModifyInfoActivity.KEY,ModifyInfoActivity.MODIFY_ADDINFO);
                    startActivity(intent);
                    finish();
                }
            }
        });

    }

    //初始化用户信息
    private void initUserInfo() {
        ScaleUser user = ScaleUser.getUser();


        String nickName = UserSpUtil.readString(Constants.IUser.NICK_NAME);
        user.setNike(nickName);


        String usid = UserSpUtil.readString(Constants.IUser.USER_ID);
        String btid = UserSpUtil.readString(Constants.IUser.BT_ID);


        LogUtils.i(TAG, "--initUserInfo--usid = " + usid + "-----btid = " + btid);
        // user.setUid(usid);
        user.setBtId(btid);


        boolean iskgModel = UserSpUtil.readBoolean(Constants.IUser.IS_KG_MODEL, true);
        user.setKgModel(iskgModel);

        int age = UserSpUtil.readInt(Constants.IUser.AGE);
        user.setAge(age);

        int sex = UserSpUtil.readInt(Constants.IUser.SEX);
        user.setSex(sex);

        String birthday = UserSpUtil.readString(Constants.IUser.BIRTHDAY);
        user.setBirthday(birthday);


        int height = UserSpUtil.readInt(Constants.IUser.HEIGHT);
        user.setHeight(height);


        float weight = UserSpUtil.readFloat(Constants.IUser.WEIGHT);
        user.setWeight(weight);


        float impedance = UserSpUtil.readFloat(Constants.IUser.IMPEDANCE);
        user.setImpedance(impedance);


        int profession = UserSpUtil.readInt(Constants.IUser.PROFESSION);//角色类型
        user.setRoleType(profession);


        LogUtils.i(TAG, "--------initUserInfo-----user--" + user);


    }

    private void FV() {
        top_left_iv = findViewById(R.id.top_left_iv);
        bluetooth_connect_station_iv = findViewById(R.id.bluetooth_connect_station_iv);
      //  top_left_iv.setImageResource(R.drawable.ehc);

        top_title_tv = findViewById(R.id.m_title_tv);
        m_left_ll_shhshj = findViewById(R.id.m_left_ll_shhshj);


//        top_title_tv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //测试
//                LogUtils.i(TAG,"----测试");
//                ThreeOneMesureResultBean mesureResult=new ThreeOneMesureResultBean(3,80,System.currentTimeMillis());
//                mesureResult.authKey=getAuthKey();
//                mesureResult.type=1;
//
//                if (mUpLoadUtil!=null)mUpLoadUtil.upLoadThreeOne(true, mesureResult);
//            }
//        });
        top_right_tv = findViewById(R.id.m_righttitle_tv);

        mDrawerLayout = findViewById(R.id.drawer_layout);

        m_left_ll = findViewById(R.id.m_left_ll);
        // FrameLayout m_m_c_fl = findViewById(R.id.m_m_c_fl);
        ll_userName_tv = findViewById(R.id.ll_userName_tv);

        m_0_tv = findViewById(R.id.m_0_tv);
        m_1_tv = findViewById(R.id.m_1_tv);
        m_2_tv = findViewById(R.id.m_2_tv);
        m_3_tv = findViewById(R.id.m_3_tv);
        m_4_tv = findViewById(R.id.m_4_tv);
        m_5_tv = findViewById(R.id.m_5_tv);
        m_6_tv = findViewById(R.id.m_6_tv);
        m_7_tv = findViewById(R.id.m_7_tv);

    }


    private BPM_Fragment mBPM_Fragment;
    private BO_Fragment mBO_Fragment;
    private ET_Fragment mET_Fragment;
    private BG_Fragment mBG_Fragment;
    private UA_Fragment mUA_Fragment;
    private TCH_Fragment mTCH_Fragment;
    private Scale_Fragment mScale_Fragment;
    private BRA_Fragment mBRA_Fragment;

    //隐藏Fragment
    private void hideAllFragment(FragmentTransaction transaction, Fragment... fragments) {
        if (transaction == null || fragments == null || fragments.length == 0) {
            return;
        }

        for (Fragment fragment : fragments) {
            if (fragment != null) transaction.hide(fragment);
        }
    }


    //设置底部的选择框
    private void setButtomSelecter(int productStyle) {

        dissLoadingDialog2();

        LogUtils.i(TAG, "---------" + productStyle);

        if (this.curDisProduct == productStyle) {//检测当前显示的是哪一个Fragment 如果是点击的是当前已显示的 就return
            return;
        }
        this.curDisProduct = productStyle;

        //把底部的按钮全部置为未选中状态
        ViewUtils.setSelects(false, m_0_tv, m_1_tv, m_2_tv, m_3_tv, m_4_tv, m_5_tv, m_6_tv, m_7_tv);

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        hideAllFragment(transaction, mBPM_Fragment, mBO_Fragment, mET_Fragment, mBG_Fragment, mUA_Fragment, mTCH_Fragment, mScale_Fragment, mBRA_Fragment);//隐藏全部的fragment

        View view = null;
        int contain = R.id.m_m_c_fl;//容器
        if (curDisProduct == 0) {
            view = m_0_tv;
            ViewUtils.setTextViewStr(top_title_tv, getString_(R.string.xueya));

            if (mBPM_Fragment == null) {
                mBPM_Fragment = new BPM_Fragment();
                mBPM_Fragment.setActivityTopTittleTv(top_title_tv);
                transaction.add(contain, mBPM_Fragment);
            } else {
                transaction.show(mBPM_Fragment);
            }

            //   replaceFragment(new BPM_Fragment(),contain);
            ViewUtils.goneView(m_left_ll_shhshj);//隐藏侧边栏的手环升级按钮
            switchingEquipment(ProductStyle.BPM);
        } else if (curDisProduct == 1) {


            view = m_1_tv;
            ViewUtils.setTextViewStr(top_title_tv, getString_(R.string.xueyang));

            if (mBO_Fragment == null) {
                mBO_Fragment = new BO_Fragment();
                mBO_Fragment.setActivityTopTittleTv(top_title_tv);
                transaction.add(contain, mBO_Fragment);
            } else {
                transaction.show(mBO_Fragment);
            }
            transaction.show(mBO_Fragment);
            //replaceFragment(new BO_Fragment(),R.id.m_m_c_fl);
            ViewUtils.goneView(m_left_ll_shhshj);//隐藏侧边栏的手环升级按钮
            switchingEquipment(ProductStyle.BLOODOXYGEN);
        } else if (curDisProduct == 2) {
            view = m_2_tv;
            ViewUtils.setTextViewStr(top_title_tv, getString_(R.string.tiwen));

            if (mET_Fragment == null) {
                mET_Fragment = new ET_Fragment();
                mET_Fragment.setActivityTopTittleTv(top_title_tv);
                transaction.add(contain, mET_Fragment);
            } else {
                transaction.show(mET_Fragment);
            }

            //  replaceFragment(new ET_Fragment(),R.id.m_m_c_fl);
            ViewUtils.goneView(m_left_ll_shhshj);//隐藏侧边栏的手环升级按钮
            switchingEquipment(ProductStyle.EAR_THERMOMETER);
        } else if (curDisProduct == 3) {
            view = m_3_tv;
            ViewUtils.setTextViewStr(top_title_tv, getString_(R.string.xuetang));

            if (mBG_Fragment == null) {
                mBG_Fragment = new BG_Fragment();
                mBG_Fragment.setActivityTopTittleTv(top_title_tv);
                transaction.add(contain, mBG_Fragment);
            } else {
                transaction.show(mBG_Fragment);
            }

            //  replaceFragment(new BG_Fragment(),R.id.m_m_c_fl);
            ViewUtils.goneView(m_left_ll_shhshj);//隐藏侧边栏的手环升级按钮
            switchingEquipment(ProductStyle.THREE_IN_ONE);
        } else if (curDisProduct == 4) {
            view = m_4_tv;
            ViewUtils.setTextViewStr(top_title_tv, getString_(R.string.niaosuan));


            if (mUA_Fragment == null) {
                mUA_Fragment = new UA_Fragment();
                mUA_Fragment.setActivityTopTittleTv(top_title_tv);
                transaction.add(contain, mUA_Fragment);
            } else {
                transaction.show(mUA_Fragment);
            }
            ViewUtils.goneView(m_left_ll_shhshj);//隐藏侧边栏的手环升级按钮
            switchingEquipment(ProductStyle.THREE_IN_ONE);
        } else if (curDisProduct == 5) {
            view = m_5_tv;
            ViewUtils.setTextViewStr(top_title_tv, getString_(R.string.zongdanguchun));

            if (mTCH_Fragment == null) {
                mTCH_Fragment = new TCH_Fragment();
                mTCH_Fragment.setActivityTopTittleTv(top_title_tv);
                transaction.add(contain, mTCH_Fragment);
            } else {
                transaction.show(mTCH_Fragment);
            }
            ViewUtils.goneView(m_left_ll_shhshj);//隐藏侧边栏的手环升级按钮
            switchingEquipment(ProductStyle.THREE_IN_ONE);
        } else if (curDisProduct == 6) {
            view = m_6_tv;
            ViewUtils.setTextViewStr(top_title_tv, getString_(R.string.tizhichen));

            if (mScale_Fragment == null) {
                mScale_Fragment = new Scale_Fragment();
                mScale_Fragment.setActivityTopTittleTv(top_title_tv);
                transaction.add(contain, mScale_Fragment);
            } else {
                transaction.show(mScale_Fragment);
            }
            ViewUtils.goneView(m_left_ll_shhshj);//隐藏侧边栏的手环升级按钮
            switchingEquipment(ProductStyle.SCALE);
        } else if (curDisProduct == 7) {
            view = m_7_tv;
            ViewUtils.setTextViewStr(top_title_tv, getString_(R.string.shouhuan));
            if (mBRA_Fragment == null) {
                mBRA_Fragment = new BRA_Fragment();
                mBRA_Fragment.setActivityTopTittleTv(top_title_tv);
                transaction.add(contain, mBRA_Fragment);
            } else {
                transaction.show(mBRA_Fragment);
            }

            if (mEhcManager!=null)mEhcManager.queryOneDayDate();//显示这个界面的时候开始去查询当前手环数据

            switchingEquipment(ProductStyle.BRACELET);
        }
        transaction.commit();
        ViewUtils.setSelect(view, true);
    }


    private void switchingEquipment(ProductStyle productStyle) {
        ViewUtils.setTextSize(top_title_tv,20);
        if (mEhcManager != null) mEhcManager.switchingEquipment(productStyle);
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.m_0_tv) {
            setButtomSelecter(0);
        } else if (id == R.id.m_1_tv) {
            setButtomSelecter(1);
        } else if (id == R.id.m_2_tv) {
            setButtomSelecter(2);
        } else if (id == R.id.m_3_tv) {
            setButtomSelecter(3);
        } else if (id == R.id.m_4_tv) {
            setButtomSelecter(4);
        } else if (id == R.id.m_5_tv) {
            setButtomSelecter(5);
        } else if (id == R.id.m_6_tv) {
            setButtomSelecter(6);
        } else if (id == R.id.m_7_tv) {
            setButtomSelecter(7);
        } else if (id == R.id.top_left_iv) {//侧边栏按钮
            top_left_iv_Ckick();
        } else if (id == R.id.m_righttitle_tv) {//趋势按钮
            top_right_tv_Ckick();
        } else if (id == R.id.m_left_ll) {
            LogUtils.i(TAG, "点击了红色侧边栏");
        }

    }


    //趋势按钮被点击
    private void top_right_tv_Ckick() {

        int key = -1;
        if (curDisProduct == 0) {//血压
            key = TrendActivity.Trend_XUEYA;
        } else if (curDisProduct == 1) {//血氧
            key = TrendActivity.Trend_XUEYANG;
        } else if (curDisProduct == 2) {//体温
            key = TrendActivity.Trend_TIWEN;
        } else if (curDisProduct == 3) {//血糖
            key = TrendActivity.Trend_XUETANG;
        } else if (curDisProduct == 4) {//尿酸
            key = TrendActivity.Trend_NIAOSUAN;
        } else if (curDisProduct == 5) {//总胆固醇
            key = TrendActivity.Trend_ZONGDANGUCHUN;
        } else if (curDisProduct == 6) {//体脂秤
            key = TrendActivity.Trend_TIZHICHENG;
        } else if (curDisProduct == 7) {//手环
            key = TrendActivity.Trend_BRA;
        }

        Intent intent = new Intent(this, TrendActivity.class);
        intent.putExtra(TrendActivity.KEY, key); //跳转到趋势界面
        startActivity(intent);

    }

    //侧边栏按钮被点击
    private void top_left_iv_Ckick() {
        if (mDrawerLayout != null) {
            if (mDrawerLayout.isDrawerOpen(m_left_ll)) {
                mDrawerLayout.closeDrawer(m_left_ll);
            } else {
                mDrawerLayout.openDrawer(m_left_ll);
            }
        }
    }

    //侧边栏--性别
    public void m_left_ll_sex(View view) {

        //ToastUtil.show("性别");
        Intent intent = new Intent(this, ModifyInfoActivity.class);
        intent.putExtra(ModifyInfoActivity.KEY, ModifyInfoActivity.MODIFY_SEX);
        startActivity(intent);


    }

    //侧边栏--退出

    public void m_left_ll_exit(View view) {
        TextTipDialog textTipDialog=new TextTipDialog(this, StringUtils.getResStr(R.string.exit_tip));
        textTipDialog.setListener(new TextTipDialog.ICancelOkBtListener() {
            @Override
            public void cancel(Dialog dialogView) {
                dialogView.cancel();
            }

            @Override
            public void ok(Dialog dialogView) {
                dialogView.cancel();
                UserSpUtil.remove(Constants.IUser.AUTH_KEY);
                UserSpUtil.remove(Constants.IUser.ehc_token);
                Delete.table(BraDb.class);//退出登录的时候删除手环同步过来的整张表
                startActivity(LoginActivity.class);
                finish();
            }
        });

        textTipDialog.show();
        textTipDialog.setTextColor(1,0xff464646);
        textTipDialog.setTextColor(2,0xff464646);
        textTipDialog.setNative_btBg(R.drawable.sp_strns_saaaaaa_r6);
        textTipDialog.setPositive_btBg(R.drawable.sp_018cd1_r6);

    }



    //侧边栏--出生年月
    public void m_left_ll_birthday(View view) {

        Intent intent = new Intent(this, ModifyInfoActivity.class);
        intent.putExtra(ModifyInfoActivity.KEY, ModifyInfoActivity.MODIFY_BIRTHDAY);
        startActivity(intent);
    }

    //侧边栏--身高
    public void m_left_ll_height(View view) {
        Intent intent = new Intent(this, ModifyInfoActivity.class);
        intent.putExtra(ModifyInfoActivity.KEY, ModifyInfoActivity.MODIFY_Height);
        startActivity(intent);
    }

    public void m_left_ll_weight(View view){
        Intent intent = new Intent(this, ModifyInfoActivity.class);
        intent.putExtra(ModifyInfoActivity.KEY, ModifyInfoActivity.MODIFY_Weight);
        startActivity(intent);
    }

    //侧边栏--关于
    public void m_left_ll_about(View view) {
        Intent intent = new Intent(this, ModifyInfoActivity.class);
        intent.putExtra(ModifyInfoActivity.KEY, ModifyInfoActivity.About);
        startActivity(intent);
       // updateVersion();

    }

    //侧边栏--手环设置
    public void m_left_ll_shhshzh(View view) {

        Intent intent = new Intent(this, ModifyInfoActivity.class);
        intent.putExtra(ModifyInfoActivity.KEY, ModifyInfoActivity.MODIFY_SHH_TIME_SET);
        startActivity(intent);

       // addd();
    }


    //侧边栏--手环升级
    public void m_left_ll_shhshj(View view) {

        LogUtils.i(TAG,"点击了手环升级按钮");


        if (mEhcManager!=null){
            BraceletManager braceletManager = mEhcManager.mBracetManager;
            if (braceletManager!=null&&braceletManager.isConnect()){
                showShHUpdateTip();
            }else {

                if (mOtaManager!=null&&!TextUtils.isEmpty(mOtaManager.getOtaMac())){
                    mOtaManager.startUpdate(MainActivity.this);
                }else {
                    ToastUtil.show(R.string.qxqbshhljzh);
                }

            }
        }


    }

    //展示提示框
    private void showShHUpdateTip() {

        TextTipDialog textTipDialog = new TextTipDialog(this, CommonLib.getString(R.string.qwshyshjshhgjm));
        textTipDialog.setListener(new TextTipDialog.ICancelOkBtListener() {
            @Override
            public void cancel(Dialog dialogView) {
                dialogView.cancel();
            }

            @Override
            public void ok(Dialog dialogView) {
                if(mEhcManager!=null&&mEhcManager.mBracetManager!=null){
                    mEhcManager.mBracetManager.sendOtaUpdate();
                }
                dialogView.cancel();
            }
        });

        textTipDialog.show();
        textTipDialog.setTextColor(1,0xff464646);
        textTipDialog.setTextColor(2,0xff464646);
        textTipDialog.setNative_btBg(R.drawable.sp_strns_saaaaaa_r6);
        textTipDialog.setPositive_btBg(R.drawable.sp_018cd1_r6);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mEhcManager != null) {
            mEhcManager.exit();
            mEhcManager = null;
        }
    }


    private long firstBackTime;

    @Override
    public void onBackPressed() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstBackTime > 2000) {
            ToastUtil.show(R.string.Touch_again_to_exit);
            firstBackTime = secondTime;
        } else {
            System.exit(0);
        }
    }


    private LoadingDialog loadingDialog2;

    public void showLoadingDialog2(String tip) {
        if (loadingDialog2 == null) {
            loadingDialog2 = new LoadingDialog(this);
            loadingDialog2.isPingBiBack = true;
        }
        if (!loadingDialog2.isShowing()) {
            loadingDialog2.show();
        }
        loadingDialog2.setTip(tip);
    }

    public void dissLoadingDialog2() {
        if (loadingDialog2 != null && loadingDialog2.isShowing()) {
            loadingDialog2.cancel();
        }
    }

    //手环里面的Viewpage的position已经改变
    public void braPageSelectedChange(int position) {
        if (mEhcManager != null) mEhcManager.braPageSelectedChange(position);
    }



    public void addd(){

        LogUtils.i(TAG,"-----addd()");
//
//        //血压计
//        BpmMesureResult mesureResult = new BpmMesureResult();
//        mesureResult.systolicPressure=92;
//        mesureResult.diastolicPressure=62;
//        mesureResult.testTime="2019-01-09 12:21:12";
//        mesureResult.pulse=72;
//        mesureResult.authKey = authKey;
//        if (mUpLoadUtil!=null)mUpLoadUtil.upLoadBloodPressure(true, mesureResult);
//

//        //血氧仪
//        BOMesureResultBean resultBean=new BOMesureResultBean();
//        resultBean.authKey = authKey;
//        resultBean.bloodOxygen = 92;
//        resultBean.pulse = 72;
//        resultBean.mesureTimeStr="2019-01-09 16:33:12";
//        if (mUpLoadUtil!=null)mUpLoadUtil.upLoadBO(true, resultBean);


//        //耳温枪
//        EarTemMesureResult result=new EarTemMesureResult();
//        result.authKey=authKey;
//        result.temperature=36.3f;
//        result.measureTimeStr="2019-01-09 13:13:25";
//        if (mUpLoadUtil!=null)mUpLoadUtil.upLoadEarTem(true, result);



        if (mBG_Fragment!=null){
            mBG_Fragment.add(authKey);
        }

//        //01血糖 02尿酸 03胆固醇
//        ThreeOneMesureResultBean san1 = new ThreeOneMesureResultBean();
//        san1.authKey=authKey;
//        //正常
//        //男（60岁及60岁以下）：149～416 umol/L
////        男（60岁以上）：250～476 umol/L
////        女（60岁及60岁以下）：89～357 umol/L
////        女（60岁以上）：190～434 umol/L
//        san1.product=2;
//        san1.mesureValue=466f;
//        san1.mesureTimeStr="2019-01-09 11:32:13";

//        //三合一 胆固醇
//        ThreeOneMesureResultBean san2 = new ThreeOneMesureResultBean();
//        san2.authKey=authKey;
//        san2.product=3;//2.86～5.98 mmol/L 正常
//        san2.mesureValue=5.01f;
//        san2.mesureTimeStr="2019-01-09 11:45:18";
//

//        if (mUpLoadUtil!=null)mUpLoadUtil.upLoadThreeOne(true, san1);
//        if (mUpLoadUtil!=null)mUpLoadUtil.upLoadThreeOne(true, san2);


//
//        //体脂秤
//        ScaleMeasureResult scaleM = new ScaleMeasureResult();
//        scaleM.authKey=authKey;
//        scaleM.measureTime = "2019-01-09 11:57:16";
//        scaleM.weight = 67.1f;
//        scaleM.fat = 22.1f;
//        scaleM.bmi=28.1f;
//        scaleM.bmr=1638;
//        scaleM.visceralFat=8;
//        scaleM.muscleVolume=24;
//        scaleM.boneVolume=4.2f;
//        scaleM.protein=37;
//        scaleM.waterRate=45f;
//        scaleM.skeletalMuscle=22.5f;
//        scaleM.bodyScore=49;
//        scaleM.bodyAge=32;
//        if (mUpLoadUtil!=null)mUpLoadUtil.upLoadScale(true, scaleM);



    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==What_Open_gps){
            checkGpsDialog();
        }
    }
}
